package clickhouse

import (
	"fmt"
	global_util "gitee.com/cheneylau/components/web-server/global/global-util"
	"github.com/cheneylew/gotools/tool"
	ch "github.com/leprosus/golang-clickhouse"
	"gorm.io/driver/clickhouse"
	"gorm.io/gorm"
)
var gormDB *gorm.DB
var CHDB *ch.Conn

func init() {
	initClickhouse2()
}

func initClickhouse()  {
	dsn := getDsn()
	dialector := clickhouse.Open(dsn)
	db, err := gorm.Open(dialector, &gorm.Config{})
	if err != nil {
		panic(err)
	}
	gormDB = db
}

func initClickhouse2()  {
	cnf, err := global_util.AppConfig()
	runmode := cnf.String("runmode")
	dbHost := cnf.String(runmode+"::chdb_host")
	dbPort := cnf.String(runmode+"::chdb_port")
	dbUser := cnf.String(runmode+"::chdb_user")
	dbPassword := cnf.String(runmode+"::chdb_password")
	//dbName := cnf.String(runmode+"::chdb_name")
	global_util.CheckErr(err, "ini config not exist!")
	if dbHost == "" {
		panic("ClickHouse DB Host未配置，如需要，在app.conf中配置！")
	}

	conn := ch.New(dbHost, tool.ToInt(dbPort), dbUser, dbPassword)
	conn.MaxMemoryUsage(100 * ch.GigaByte) //控制clickhouse最大用量
	ch.Debug(func(message string) {

	})
	CHDB = conn
}

func getDsn() string {
	cnf, err := global_util.AppConfig()
	runmode := cnf.String("runmode")
	dbHost := cnf.String(runmode+"::chdb_host")
	dbPort := cnf.String(runmode+"::chdb_port")
	dbUser := cnf.String(runmode+"::chdb_user")
	dbPassword := cnf.String(runmode+"::chdb_password")
	dbName := cnf.String(runmode+"::chdb_name")
	global_util.CheckErr(err, "ini config not exist!")
	if dbHost == "" {
		panic("ClickHouse DB Host未配置，如需要，在app.conf中配置！")
	}

	return fmt.Sprintf("tcp://%s:%s?database=%s&username=%s&password=%s&read_timeout=10&write_timeout=20",
		dbHost,dbPort,dbName,dbUser,dbPassword)
}

func FetchWithResultMap(sql string) ([]map[string]interface{}, error) {
	iter, err := CHDB.Fetch(sql)
	if err != nil {
		return nil, err
	}
	data := make([]map[string]interface{}, 0)
	for iter.Next() {
		result := iter.Result
		mp := make(map[string]interface{}, 0)
		for _, v1 := range result.Columns() {
			r, _:= result.String(v1)
			mp[v1] = r
		}
		data = append(data, mp)
	}
	return data, nil
}
